package com.haiheng.bookmusic.base

import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener
import com.haiheng.bookmusic.utils.GlideUtils
import com.haiheng.library.log.LogUtils
import com.haiheng.voiceandbook.Constants
import com.haiheng.voiceandbook.Constants.Companion.BASE_URL
import com.haiheng.voiceandbook.Constants.Companion.BOOK_PATH
import com.haiheng.voiceandbook.Constants.Companion.PRE_PACKAGE_BOOK_PATH
import com.haiheng.voiceandbook.MyApplication
import com.haiheng.voiceandbook.R
import com.haiheng.voiceandbook.ScreenSaverActivity
import com.haiheng.voiceandbook.adapter.BookTitleListAdapter
import com.haiheng.voiceandbook.commo.EpubBean
import com.haiheng.voiceandbook.commo.SettingDialog
import com.haiheng.voiceandbook.common.BookDetailInfoDto
import com.haiheng.voiceandbook.common.DocDto
import com.haiheng.voiceandbook.databinding.DialogBookInfoShowBinding
import com.haiheng.voiceandbook.databinding.DialogBookShowBinding
import com.haiheng.voiceandbook.treeview.adapter.RecyclerAdapter
import com.haiheng.voiceandbook.treeview.interfaces.ItemDataClickListener
import com.haiheng.voiceandbook.utils.*
import com.haiheng.voiceandbook.view.BookWebView
import com.haiheng.voiceandbook.view.LoadingDialog
import com.haiheng.voiceandbook.view.MyRecyclerView
import com.haiheng.voiceandbook.viewmodel.BookViewModel
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import nl.siegmann.epublib.domain.Resource
import nl.siegmann.epublib.domain.SpineReference
import nl.siegmann.epublib.domain.TOCReference
import nl.siegmann.epublib.epub.EpubReader
import org.geometerplus.android.fbreader.AppNotifier
import org.geometerplus.android.fbreader.FBReader
import org.geometerplus.android.fbreader.NewFBReaderActivity
import org.geometerplus.android.fbreader.api.FBReaderIntents
import org.geometerplus.fbreader.fbreader.FBReaderApp.Notifier
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


abstract class BaseActivity : AppCompatActivity(), OnPageChangeListener, OnLoadCompleteListener,
    ItemDataClickListener {
    protected val TAG = this.javaClass.simpleName

    //目录
    var docAdapter: RecyclerAdapter? = null
    var bookViewModel: BookViewModel? = null
    var docTitle = ""
    var resHref = ""
    var openBookDialog:OpenBookDialog? = null;
    private var  startReadTime:Long = 0 //开始播放时间
    private var  totalReadTime:Long = 0 //总共播放时长，单位s
    //设置屏保
    private val mHandler01 = Handler()
    private val mHandler02 = Handler()

    /* 上一次User有动作的Time Stamp */
    private var lastUpdateTime: Date? = null
    /* 计算User有几秒没有动作的 */
    private var timePeriod: Long = 0
    /* 静止超过N秒将自动进入屏保 */
    private val mHoldStillTime = Constants.getSreenSaverTime()
    /*标识当前是否进入了屏保*/
    private var isRunScreenSaver = false
    /*时间间隔*/
    private val intervalScreenSaver: Long = 1000
    private val intervalKeypadeSaver: Long = 1000

    override fun onCilick(item: DocDto?) {
//        if (!zipResult) {
//            Toast.makeText(this, "图书正在加载，请稍后...", Toast.LENGTH_SHORT).show()
//            return
//        }
//        val path = item?.resHref?.let {
//            docTitle = item.title!!
//            resHref = item.resHref!!
//            getPageHref(it, name)
//        }
//
//       bookShowBinding?.webView?.loadUrl("file://${path}")
        var preBookPath = "${PRE_PACKAGE_BOOK_PATH}/${mFileName}"
        var bookPath = "${BOOK_PATH}/${mFileName}"
        Log.e(TAG, "onItemClick: " + bookPath)
        if (FileUtils.fileExists(preBookPath)){
            var intent = Intent()
            intent.setData(Uri.parse(preBookPath))
            openBookDialog?.openBook(intent,item?.title)
        }else if (FileUtils.fileExists(bookPath)){
            var intent = Intent()
            intent.setData(Uri.parse(bookPath))
            openBookDialog?.openBook(intent,item?.title)

//            val intent = Intent(applicationContext, FBReader::class.java)
//                .setAction(FBReaderIntents.Action.VIEW)
//                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
//            intent.setData(Uri.parse(bookPath))
//            startActivity(intent)
        }else{
            Toast.makeText(this, "图书正在加载，请稍后...", Toast.LENGTH_SHORT).show()
            return
        }

        bookShowBinding?.tvList?.visibility = View.VISIBLE
        bookShowBinding?.webView?.visibility = View.GONE
        bookShowBinding?.bookView?.visibility = View.VISIBLE
        bookShowBinding?.recyclerView?.visibility = View.GONE
        bookShowBinding?.tvProgress?.visibility = View.GONE

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Density.setDensity(getApplication(), this)
        bookViewModel = ViewModelProvider(
            this,
            ViewModelProvider.NewInstanceFactory()
        ).get(BookViewModel::class.java)
        initStatus()
        intiLayout()
        initView()
        initListener()
        initData()
        initDataChange()
        /* 初始取得User可触碰屏幕的时间 */
        lastUpdateTime = Date(System.currentTimeMillis())
    }




    abstract fun initDataChange()

    abstract fun initListener()

    /**
     * 初始化书籍
     */
    abstract fun initData()

    /**
     * 初始视图
     */
    abstract fun initView()

    /**
     * 设置布局
     *
     * @return
     */
    abstract fun intiLayout()

    /**
     * 设置沉侵式状态栏
     */
    private fun initStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            val flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
            val flagTranslucentNavigation =
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                val window = window
                val attributes = window.attributes
                attributes.flags = attributes.flags or flagTranslucentNavigation
                window.attributes = attributes
                getWindow().statusBarColor = Color.TRANSPARENT
            } else {
                val window = window
                val attributes = window.attributes
                attributes.flags =
                    attributes.flags or (flagTranslucentStatus or flagTranslucentNavigation)
                window.attributes = attributes
            }
        }
    }

    private var loadingDialog //加载提示框
            : LoadingDialog? = null

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
//        LogUtils.d("用户有触摸屏幕的操作，重置计时器"+this.hashCode())
        updateUserActionTime()
        if (ev != null) {
            when (ev.action) {
                MotionEvent.ACTION_DOWN -> {

                }
                MotionEvent.ACTION_UP -> {
                    RxScreenCickTimerUtil.cancel()
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    private fun initDownTimeTask() {

    }

    open fun getLoadingDialog(): LoadingDialog {
        if (null == loadingDialog) {
            loadingDialog = LoadingDialog(this)
            //点击空白处Dialog不消失
            loadingDialog!!.setCanceledOnTouchOutside(false)
        }
        return loadingDialog!!
    }

    open fun showLoadingDialog() {
        getLoadingDialog().showDialog()
    }

    open fun hideLoadingDialog() {
        getLoadingDialog().dismiss()
    }


    /**
     * 显示书的基本详情信息
     */
    protected fun showBookDetailDialog(data: BookDetailInfoDto?) {

        Density.setDensity(MyApplication.getInstance(), this)
        val binding = DialogBookInfoShowBinding.inflate(LayoutInflater.from(this), null, false)
        val dialog: Dialog =
            SmartDialogUtils.getDialogNotTouchOutside(this, binding.root)
        binding.ivClose.setOnClickListener {
            dialog.dismiss()
        }
        if (data != null) {
            GlideUtils.load(this, data.coverImg, binding.ivLeft)
        }

        val url =
            "${BASE_URL}webview/index.html#/pages/bookPage/bookPage?id=${data?.bookId}&libraryNo=${Constants.getLibraryCode()}&PhysicalAddress=${Constants.getDevicesId()}"

        val bitmap: Bitmap = ZXingUtils.createQRImage(
            url,
            DisplayUtil.dip2px(this, 40f),
            DisplayUtil.dip2px(this, 40f)
        )
        binding.ivCode.setImageBitmap(bitmap)

        binding.tvName.text = data?.bookName
        binding.tvAuthor.text = data?.author
        binding.tvContent.text = data?.summary
        binding.tvOk.setOnClickListener {
            dialog.dismiss()
            toSeeBook(data)
            bookViewModel?.reportReadTimes(data?.bookId)
        }
        dialog.show()
    }

    val fixedThreadPool: ExecutorService = Executors.newFixedThreadPool(10)

    /**
     * 使用ID作为书籍名字
     * 解压之后的文件名字
     *
     */
    var mFileName: String? = null
    var name: String? = null
    var bookShowBinding: DialogBookShowBinding? = null

    /**
     * 去看书
     */
    private fun toSeeBook(data: BookDetailInfoDto?) {
        if (TextUtils.isEmpty(data?.path)) {
            return
        }

        Density.setDensity(MyApplication.getInstance(), this)
        /**
         * 使用ID作为书籍名字
         */
//        name = data?.bookId.toString()
        if (!TextUtils.isEmpty(data?.path)){
            //path:https://yidu.seaeverit.com/book_mgr/resource/zybook/116830602五代：宋辽金夏：战争史笔记：[修订版].epub?1634094314210
            var path  = data?.path
            name = path?.let { path.substring(it.lastIndexOf("/")+1,path.lastIndexOf("?")) };
            Log.d(TAG, "下载文件名称: "+name)
        }
        /**
         * 确定后缀
         */
//        mFileName = if ("pdf".equals(data?.bookType)) "${name}.pdf" else "${name}.epub"
        mFileName = if ("pdf".equals(data?.bookType)) "${name}.pdf" else "${name}"

        val file = File(BOOK_PATH + "/" + mFileName)
//        val file = File("/storage/emulated/0/BOOK/1449321409770717185.epub")

        bookShowBinding = DialogBookShowBinding.inflate(LayoutInflater.from(this), null, false)
//        val dialog = SmartDialogUtils.getDialogNotTouchOutside(this, bookShowBinding!!.root)
        openBookDialog = OpenBookDialog(this, bookShowBinding,bookShowBinding!!.root)

        openBookDialog!!.setOnDismissListener(object : DialogInterface.OnDismissListener {
            override fun onDismiss(dialog: DialogInterface?) {
                try {
                    data?.bookId?.let { it1 -> reportReading(it1) }
                }catch (ex:Exception){

                }
            }

        })
        bookShowBinding?.webView?.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
                view.loadUrl(url!!)
                return true
            }
        }
        docAdapter = RecyclerAdapter(this, this)
        bookShowBinding?.recyclerView?.layoutManager = LinearLayoutManager(this)
        bookShowBinding?.recyclerView?.adapter = docAdapter

        var list = JSONObject.parseArray(data?.directory, DocDto::class.java)

        data?.run {
            if (bookType.equals("pdf") || path.contains("pdf")) {
                bookShowBinding?.tvList?.visibility = View.GONE
                bookShowBinding?.recyclerView?.visibility = View.GONE
                bookShowBinding?.webView?.visibility = View.VISIBLE

            } else {
                //epub
                bookShowBinding?.tvList?.visibility = View.GONE
                bookShowBinding?.recyclerView?.visibility = View.VISIBLE
                bookShowBinding?.webView?.visibility = View.GONE
                if (list.isNullOrEmpty()) {
                    Log.e(TAG, "获取网络目录失败: ")
                    bookShowBinding?.tvProgress?.visibility = View.VISIBLE
                } else {
                    bookShowBinding?.tvProgress?.visibility = View.GONE
                    //如果网络返回了目录，直接显示
                    docAdapter?.addAll(list, 0)
                    docAdapter?.notifyDataSetChanged()

                }

            }
        }

        bookShowBinding?.tvOk?.setOnClickListener {
            showQcoreDialog(data?.bookId)
//            openBookDialog!!!!.openMenu()
        }
        bookShowBinding?.ivClose?.setOnClickListener {
            openBookDialog!!!!.dismiss()


        }
        bookShowBinding?.tvList?.setOnClickListener {
            bookShowBinding?.tvList?.visibility = View.GONE
            bookShowBinding?.webView?.visibility = View.GONE
            bookShowBinding?.recyclerView?.visibility = View.VISIBLE
            bookShowBinding?.tvProgress?.visibility = View.GONE

        }

        startReadTime = System.currentTimeMillis()
        openBookDialog!!.show()
        zipResult = false
//        var preFileName = data?.path;
//        preFileName = preFileName?.subSequence(preFileName.lastIndexOf("/"),preFileName.length).toString()
        val prePackageFile = File( "${PRE_PACKAGE_BOOK_PATH}/${mFileName}")

        if (file.exists()){
//            openBook(dialog,file)
        }

        if (prePackageFile.exists()){
            Log.e(TAG, "toSeeBook: 走预装文件...")
            if (data != null) {
//                tryOpenBook(data.bookType, prePackageFile)
            }
        }else if (file.exists() && file.length() == data?.fileLength) {
            //有缓存
            Log.e(TAG, "toSeeBook: 走缓存...")
//            tryOpenBook(data.bookType, file)
//            openBook(dialog,file)
        } else {
            //下载书籍
            downLoadBook(
                data?.bookType,
                mFileName,
                data?.path,
            )
        }

    }

    var zipResult = false

    private fun openBook(dialog:OpenBookDialog,file: File){
        if (file.exists()){
            lifecycleScope.launch(Dispatchers.Main) {
                bookShowBinding?.tvProgress?.visibility = View.GONE
                hideLoadingDialog()
                bookShowBinding?.tvList?.visibility = View.VISIBLE
                bookShowBinding?.webView?.visibility = View.GONE
                bookShowBinding?.bookView?.visibility = View.VISIBLE
                bookShowBinding?.recyclerView?.visibility = View.GONE
                bookShowBinding?.tvProgress?.visibility = View.GONE
            }
//            var path  = "/storage/emulated/0/BOOK/1449321409770717185.epub";
            var intent = Intent()
            intent.setData(Uri.parse(file.absolutePath))
            dialog.openBook(intent,"")
            return
        }
    }

    /**
     * 下载书籍
     */
    private fun downLoadBook(
        bookType: String?,
        fileName: String?,
        url: String?,
    ) {
        //http://218.17.192.253:9000/zybook/112779702画里画外话楚辞.epub?1634469377647
        Log.e(TAG, "toSeeBook: 走下载...")
        showLoadingDialog()
        lifecycleScope.launch(Dispatchers.IO) {
            //请求下载文件拿到下载结果
//            val result = bookViewModel?.downLoadUrl(url?.split("com")?.get(1), fileName, bookType)
            val result = bookViewModel?.downLoadUrl(url, fileName, bookType)
            //如果返回1则代表下载失败
            if (!"1".equals(result)) {
                val file = File(BOOK_PATH, fileName)
                Log.e(TAG, "下载成功：${file}")
                hideLoadingDialog()
//                tryOpenBook(bookType, file);
            } else {
                withContext(Dispatchers.Main){
                    bookShowBinding?.tvProgress?.text = "下载失败，请稍后再试"
                }
            }

        }


    }

    /**
     * 尝试打开书籍
     */
    private fun tryOpenBook(bookType: String?, file: File) {
        /**
         * pdf书籍
         */
        if (bookType.equals("pdf")) {
            openPdf(file)
        }
        //epub
        else {
            openEpub(file)

//            val intent = Intent(applicationContext, NewFBReaderActivity::class.java)
//                .setAction(FBReaderIntents.Action.VIEW)
//                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
//            var bundle = Bundle()
//            intent.setData(Uri.parse(file.absolutePath))
//            startActivity(intent)
        }

    }

    /**
     *  打开epub书籍
     */
    private fun openEpub(file: File) {
        lifecycleScope.launch(Dispatchers.Main) {
            //先看看 之前是否设置了网络目录，如果没有那就自己在解析文件里的目录
            val count = bookShowBinding?.recyclerView?.adapter?.itemCount
            //没有显示目录
            if (count == null || count <= 0) {
                val docList = getNativeDocList(file)
                docAdapter?.addAll(docList, 0)
                docAdapter?.notifyDataSetChanged()
            }
            withContext(Dispatchers.IO) {
                //解压
                zipResult = FileUtils.unzipFile(file.absolutePath, "${BOOK_PATH}/${name}")
                withContext(Dispatchers.Main) {
                    bookShowBinding?.tvProgress?.visibility = View.GONE
                    hideLoadingDialog()
                }
            }


        }

    }


    /**
     * 打开pdf
     */
    private fun openPdf(file: File) {
        lifecycleScope.launch(Dispatchers.Main) {
            showLoadingDialog()
            bookShowBinding?.webView?.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=${file.absolutePath}")
            hideLoadingDialog()
            bookShowBinding?.tvProgress?.visibility = View.GONE
        }


    }


    /**
     * 展示电子书二维码
     */
    private fun showQcoreDialog(id: String?) {
        Density.setDensity(MyApplication.getInstance(), this)


        val dialog: Dialog = SmartDialogUtils.getDialogNotTouchOutside(this, R.layout.dialog_q_code)
        val iv_q_code = dialog.findViewById<ImageView>(R.id.iv_q_code) as ImageView
        val tvOk = dialog.findViewById<View>(R.id.tv_ok) as TextView
        val tvTitle = dialog.findViewById<View>(R.id.tv_title) as TextView


        val url =
            "${BASE_URL}webview/index.html#/pages/bookPage/bookPage?id=${id}&libraryNo=${Constants.getLibraryCode()}&PhysicalAddress=${Constants.getDevicesId()}"
        Log.e(TAG, "showQcoreDialog: ${url}")
        val bitmap: Bitmap = ZXingUtils.createQRImage(
            url,
            DisplayUtil.dip2px(this, 262f),
            DisplayUtil.dip2px(this, 262f)
        )
        iv_q_code.setImageBitmap(bitmap)
        tvTitle.setText("打开微信扫一扫即可阅读")
        tvOk.setOnClickListener {
            dialog.dismiss()

        }
        dialog.show()
    }

    override fun onPageChanged(page: Int, pageCount: Int) {

    }

    override fun loadComplete(nbPages: Int) {

    }

    /**
     * 自己手动解析目录树结构
     */
    fun getNativeDocList(file: File): List<DocDto> {
        Log.e(TAG, "获取本地目录: --------")
        val jsonArray = getTableOfContent(file)
        val result = jsonArray?.toJSONString()
        val list = JSONObject.parseArray(result, DocDto::class.java)
        Log.e(TAG, "intiLayout: ${list}")
        return list
    }

    /**
     *通过文件解析目录
     * 树结构
     */
    fun getTableOfContent(file: File): JSONArray? {

        /**
         * 解析标题
         */
        val inputStream: InputStream = FileInputStream(file)
        val epubReader = EpubReader()
        val book = epubReader.readEpub(inputStream)
        val toc = book.tableOfContents
        val refs = toc.tocReferences


        if (refs != null && !refs.isEmpty()) {
            val ja = JSONArray()

            refs.forEach {
                ja.add(extractRef(it))
            }


            return ja
        }
        return null
    }

    private fun extractRef(ref: TOCReference): JSONObject? {
        val jo = JSONObject()
        val res = ref.resource
        jo.put("title", ref.title)
        jo.put("fragmentId", ref.fragmentId)
        jo.put("resHref", res.href)
        jo.put("resId", res.id)
        val refs = ref.children
        if (refs != null && !refs.isEmpty()) {
            val ja = JSONArray()
            refs.forEach {
                ja.add(extractRef(it))
            }
            jo.put("children", ja)
        }
        return jo
    }

    /**
     * 关联本地的连接
     * 获取连接
     */
    private fun getPageHref(href: String, firName: String?): String? {
        Log.e(TAG, "getPageHref: href = ${href} and firName = ${firName}")
        var pageHref = href
        val opfpath = FileUtils.getPathOPF(FileUtils.getEpubFolderPath(firName))
        Log.e(TAG, "getPageHref:opfpath =  ${opfpath}")
        val result = FileUtils.checkOPFInRootDirectory(FileUtils.getEpubFolderPath(firName))
        Log.e(TAG, "getPageHref: ${result}")
        pageHref = if (FileUtils.checkOPFInRootDirectory(FileUtils.getEpubFolderPath(firName))) {
            FileUtils.getEpubFolderPath(firName).toString() + "/" + pageHref
        } else {
            FileUtils.getEpubFolderPath(firName).toString() + "/" + opfpath + "/" + pageHref
        }
        Log.e(TAG, "getPageHref:${pageHref} ")
        return pageHref
    }

    /**
     * 展示提示
     */
    public fun showTipsDialog(tips: String) {
        Density.setDensity(getApplication(), this)
        val dialog: Dialog = SmartDialogUtils.getDialogNotTouchOutside(this, R.layout.dialog_tips)
        val tv_tips = dialog.findViewById<View>(R.id.tv_tips) as TextView
        val tvOk = dialog.findViewById<View>(R.id.tv_ok) as TextView

        tv_tips.setText(tips)
        tvOk.setOnClickListener {
            dialog.dismiss()

        }
        dialog.show()
    }

    fun reportReading(bookId:String){
        if (startReadTime > 0){
            var readTime = (System.currentTimeMillis() - startReadTime)/1000
            Log.e(TAG,"hwz reportReading:${readTime}")
            if (readTime > 0){
                bookViewModel?.reportReading(bookId,readTime)
            }
        }
    }

    /**
     * 计时线程
     */
    private val mTask01: Runnable = object : Runnable {
        override fun run() {
            val timeNow = Date(System.currentTimeMillis())
            /* 计算User静止不动作的时间间距 */
            /**当前的系统时间 - 上次触摸屏幕的时间 = 静止不动的时间 */
            timePeriod = timeNow.time - lastUpdateTime!!.time
            /*将静止时间毫秒换算成秒*/
            val timePeriodSecond = timePeriod.toFloat() / 1000
            if (timePeriodSecond > mHoldStillTime) {
                if (isRunScreenSaver == false) { //说明没有进入屏保
                    /* 启动线程去显示屏保 */
                    mHandler02.postAtTime(mTask02, intervalScreenSaver)
                    /*显示屏保置为true*/
                    isRunScreenSaver = true
                } else {
                    /*屏保正在显示中*/

                }
            } else {
                /*说明静止之间没有超过规定时长*/
                isRunScreenSaver = false
            }
            /*反复调用自己进行检查*/
            mHandler01.postDelayed(this, intervalKeypadeSaver)
        }
    }

    /**
     * 持续屏保显示线程
     */
    private val mTask02: Runnable = object : Runnable {
        override fun run() {
            if (isRunScreenSaver == true) {
                //如果屏保正在显示，就计算不断持续显示
                // hideOriginalLayout();
                showScreenSaver()
                mHandler02.postDelayed(this, intervalScreenSaver)
            } else {
                mHandler02.removeCallbacks(this) //如果屏保没有显示则移除线程
            }
        }
    }

    /**
     * 显示屏保
     */
    private fun showScreenSaver() {
        if (Constants.isOpenSreenSaver()){
//            LogUtils.d(" 显示屏保------>"+this)
            if (!(this is ScreenSaverActivity) && Constants.isPicFileExists()){
                val intent = Intent(this, ScreenSaverActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) // 设置标志确保只有一个实例
                startActivity(intent)

            }
        }
    }

    /*用户有操作的时候不断重置静止时间和上次操作的时间*/
    fun updateUserActionTime() {
        val timeNow = Date(System.currentTimeMillis())
        timePeriod = timeNow.time - lastUpdateTime!!.time
        lastUpdateTime!!.time = timeNow.time
    }

    override fun onResume() {
        /*activity显示的时候启动线程*/
        lastUpdateTime = Date(System.currentTimeMillis())
        isRunScreenSaver = false;
        mHandler01.postAtTime(mTask01, intervalKeypadeSaver)
        super.onResume()
    }
    override fun onPause() {
        /*activity不可见的时候取消线程*/
        mHandler01.removeCallbacks(mTask01)
        mHandler02.removeCallbacks(mTask02)
        super.onPause()
    }
}